package com.hsogoo.collate.batch;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.core.io.ClassPathResource;

/**
 * @Author huangsaigang
 * Created @2019-10-28.
 */
@Slf4j
public class PersistCollateFileTasklet implements Tasklet {

    @Override
    public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
        log.info("PersistCollateFileTasklet.executing...");

        JobParameters jobParameters = stepContribution.getStepExecution().getJobExecution().getJobParameters();
        String taskName = jobParameters.getString("taskName");
        String targetFieldsMapper = jobParameters.getString("targetFieldMapper");
        String targetFieldSeparator = jobParameters.getString("targetFieldSeparator");
        String localFilePath = jobParameters.getString("localFilePath");

        FlatFileItemReader<CollateFields> collateReader = new FlatFileItemReader();

//        collateReader.setResource(new FileSystemResource(localFilePath));
        collateReader.setResource(new ClassPathResource("test.txt"));

        String[] targetFieldNames = targetFieldsMapper.split(",");
        String[] targetFieldMapper = new String[targetFieldNames.length];
        for (int i = 0; i < targetFieldNames.length; ) {
            targetFieldMapper[i] = "field" + i++;
        }
        DefaultLineMapper<CollateFields> lineMapper = new DefaultLineMapper();
        DelimitedLineTokenizer delimitedLineTokenizer = new DelimitedLineTokenizer();
        delimitedLineTokenizer.setDelimiter(targetFieldSeparator);
        delimitedLineTokenizer.setNames(targetFieldMapper);
        lineMapper.setLineTokenizer(delimitedLineTokenizer);
        CollateFieldSetMapper collateFieldSetMapper = new CollateFieldSetMapper();
        lineMapper.setFieldSetMapper(collateFieldSetMapper);
        collateReader.setLineMapper(lineMapper);
        collateReader.open(new ExecutionContext());

        CollateFields collateFields = collateReader.read();

        log.info("[{}] persist collate file use [{}] split by [{}]", taskName, targetFieldsMapper, targetFieldSeparator);
        return RepeatStatus.FINISHED;
    }
}
